<template>
  <div class="custom-tree-container" style="text-align: center">
    <el-row :gutter="20">
      <el-col :span="12" :offset="6">
        <el-tree :data="menu" node-key="name" draggable default-expand-all :expand-on-click-node="false">
          <template #default="{ node, data }">
            <span class="custom-tree-node">
              <span>
                <component :is="data.meta.icon" style="width: 16px; height: 16px"></component>
                {{ data.meta.title ?? "" }}
              </span>
              <span>
                <el-button link :icon="Plus" @click="append(data, DialogType.add)" />
                <el-button link :icon="Edit" @click="append(data, DialogType.edit)" />
                <el-button link :icon="Minus" @click="remove(node, data)" />
              </span>
            </span>
          </template>
        </el-tree>
        <el-button style="margin-top: 10px" type="primary" @click="updateData">保存</el-button>
        <el-button style="margin-top: 10px" type="primary" @click="loadData">重置</el-button>
      </el-col>
    </el-row>

    <MenuDialog ref="menuDialogRef" @success="addMenu"></MenuDialog>
  </div>
</template>

<script lang="ts" setup>
import { onMounted, ref } from "vue";
import type Node from "element-plus/es/components/tree/src/model/node";
import { simpleUserTableDataController } from "@/api/modules/dwh";
import MenuDialog from "@/views/dwh/menu/components/menuDialog.vue";
import { Edit, Minus, Plus } from "@element-plus/icons-vue";
import { DialogType } from "@/utils/dict";
import { useRoute, useRouter } from "vue-router";
import { ElMessage } from "element-plus";

interface Tree {
  path: string;
  name: string;
  redirect: string;
  meta: { title: string };
  children?: Tree[];
}

const menuDialogRef = ref<InstanceType<typeof MenuDialog> | null>(null);

const selectMenu = ref<Tree>();

const append = (data: Tree, dialogType: DialogType) => {
  selectMenu.value = data;
  if (dialogType == DialogType.add) {
    let tree = JSON.parse(JSON.stringify(data));
    tree.path = "";
    tree.name = "";
    tree.meta.title = "";
    tree.children = [];
    tree.redirect = "";
    menuDialogRef.value?.show(tree, dialogType);
  } else if (dialogType == DialogType.edit) {
    menuDialogRef.value?.show(data, dialogType);
  }
};
let router = useRouter();
const addMenu = (data: Tree, dialogType: DialogType) => {
  if (dialogType == DialogType.add) {
    if (selectMenu.value) {
      if (!selectMenu.value.children) {
        selectMenu.value.children = [];
      }
      selectMenu.value.children.push(data);
    }
    menu.value = [...menu.value];
  } else if (dialogType == DialogType.edit) {
    Object.assign(selectMenu.value, data);
    menu.value = [...menu.value];
  } else if (dialogType == DialogType.Null) {
    menu.value = [...menu.value, data];
  }
};

const remove = (node: Node, data: Tree) => {
  const parent = node.parent;
  const children: Tree[] = parent.data.children || parent.data;
  const index = children.findIndex(d => d.name === data.name);
  children.splice(index, 1);
  menu.value = [...menu.value];
};

const menu = ref<Tree[]>([]);
let route = useRoute();
onMounted(() => {
  loadData();
  let query = route.query;
  if (query.path && query.tableInfoId) {
    let tree = {
      path: query.path + "/" + query.tableInfoId,
      name: "tableData" + query.tableInfoId,
      component: "/dwh/tableData/index",
      meta: { title: query.title },
      children: []
    };
    menuDialogRef.value?.show(tree, DialogType.Null);
  }
});
const menuTableId = import.meta.env.VITE_MENU_TABLE_ID;
const menuItemId = ref("");
const updateData = async () => {
  await simpleUserTableDataController.saveUserTableDataUsingPOST({
    tableInfoId: menuTableId,
    columnValueParams: [{ columnCode: "menu_items", value: JSON.stringify(menu.value) }],
    whereColumnValueParams: [{ columnCode: "id", value: menuItemId.value }]
  });
  router.replace("/dwh/menu");
  await loadData();
  ElMessage.success("保存成功");
};

const loadData = async () => {
  let { data } = await simpleUserTableDataController.pageUserTableDataUsingPOST({
    page: { pageIndex: 1, pageSize: 100 },
    query: { tableInfoId: Number(menuTableId) }
  });

  menu.value = JSON.parse(data[0].tableData.find((item: any) => item.columnCode === "menu_items")?.value);
  menuItemId.value = JSON.parse(data[0].tableData.find((item: any) => item.columnCode === "id")?.value);
};
</script>

<style>
.custom-tree-node {
  display: flex;
  flex: 1;
  align-items: center;
  justify-content: space-between;
  padding-right: 8px;
  font-size: 14px;
}
</style>
